const MemberCard = require('../models/MemberCard');
const CardTransaction = require('../models/CardTransaction');
const { Op } = require('sequelize');
const sequelize = require('../config/database');

// 创建会员卡
const createMemberCard = async (req, res) => {
  const t = await sequelize.transaction();
  try {
    const { customerId, cardType, cardName, balance, remainingTimes } = req.body;

    // 参数验证
    if (!customerId || !cardType) {
      return res.status(400).json({
        code: 400,
        message: '客户ID和卡类型为必填项'
      });
    }

    // 创建会员卡
    const memberCard = await MemberCard.create({
      customerId,
      cardType,
      cardName,
      balance: cardType === '储值卡' ? balance || 0 : null,
      remainingTimes: cardType === '次卡' ? remainingTimes || 0 : null,
      status: '正常'
    }, { transaction: t });

    // 如果有初始充值，创建充值交易记录
    if ((cardType === '储值卡' && balance > 0) || (cardType === '次卡' && remainingTimes > 0)) {
      await CardTransaction.create({
        cardId: memberCard.id,
        type: '充值',
        amount: cardType === '储值卡' ? balance : null,
        times: cardType === '次卡' ? remainingTimes : null,
        beforeBalance: 0,
        afterBalance: cardType === '储值卡' ? balance : null,
        beforeTimes: 0,
        afterTimes: cardType === '次卡' ? remainingTimes : null,
        remark: '开卡初始充值'
      }, { transaction: t });
    }

    await t.commit();

    res.status(201).json({
      code: 200,
      message: '会员卡创建成功',
      data: memberCard
    });

  } catch (error) {
    await t.rollback();
    console.error('创建会员卡错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取会员卡列表
const getMemberCards = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, customerId, cardType, status } = req.body;
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const where = {};
    if (customerId) where.customerId = customerId;
    if (cardType) where.cardType = cardType;
    if (status) where.status = status;

    const { count, rows } = await MemberCard.findAndCountAll({
      where,
      include: [{
        association: 'customer',
        attributes: ['name', 'phone']
      }],
      order: [['createdAt', 'DESC']],
      offset,
      limit: pageSize
    });

    res.json({
      code: 200,
      message: '获取会员卡列表成功',
      data: {
        total: count,
        page,
        pageSize,
        list: rows
      }
    });

  } catch (error) {
    console.error('获取会员卡列表错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取会员卡详情
const getMemberCardById = async (req, res) => {
  try {
    const { id } = req.body;

    const memberCard = await MemberCard.findByPk(id, {
      include: [{
        association: 'customer',
        attributes: ['name', 'phone']
      }]
    });

    if (!memberCard) {
      return res.status(404).json({
        code: 404,
        message: '会员卡不存在'
      });
    }

    res.json({
      code: 200,
      message: '获取会员卡详情成功',
      data: memberCard
    });

  } catch (error) {
    console.error('获取会员卡详情错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 更新会员卡
const updateMemberCard = async (req, res) => {
  try {
    const { id, cardName, status } = req.body;

    const memberCard = await MemberCard.findByPk(id);
    if (!memberCard) {
      return res.status(404).json({
        code: 404,
        message: '会员卡不存在'
      });
    }

    // 更新会员卡信息
    await memberCard.update({
      cardName,
      status
    });

    res.json({
      code: 200,
      message: '会员卡更新成功',
      data: memberCard
    });

  } catch (error) {
    console.error('更新会员卡错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 删除会员卡
const deleteMemberCard = async (req, res) => {
  try {
    const { id } = req.body;

    const memberCard = await MemberCard.findByPk(id);
    if (!memberCard) {
      return res.status(404).json({
        code: 404,
        message: '会员卡不存在'
      });
    }

    await memberCard.destroy(); // 软删除

    res.json({
      code: 200,
      message: '会员卡删除成功'
    });

  } catch (error) {
    console.error('删除会员卡错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 会员卡充值
const rechargeCard = async (req, res) => {
  const t = await sequelize.transaction();
  try {
    const { cardId, amount, times, remark } = req.body;

    const memberCard = await MemberCard.findByPk(cardId, { transaction: t });
    if (!memberCard) {
      return res.status(404).json({
        code: 404,
        message: '会员卡不存在'
      });
    }

    if (memberCard.status !== '正常') {
      return res.status(400).json({
        code: 400,
        message: '会员卡状态异常，无法充值'
      });
    }

    // 储值卡充值
    if (memberCard.cardType === '储值卡' && amount) {
      const beforeBalance = memberCard.balance;
      const afterBalance = Number(beforeBalance) + Number(amount);

      // 更新卡余额
      await memberCard.update({
        balance: afterBalance
      }, { transaction: t });

      // 创建充值记录
      await CardTransaction.create({
        cardId,
        type: '充值',
        amount,
        beforeBalance,
        afterBalance,
        remark
      }, { transaction: t });
    }
    // 次卡充值
    else if (memberCard.cardType === '次卡' && times) {
      const beforeTimes = memberCard.remainingTimes;
      const afterTimes = beforeTimes + times;

      // 更新卡次数
      await memberCard.update({
        remainingTimes: afterTimes
      }, { transaction: t });

      // 创建充值记录
      await CardTransaction.create({
        cardId,
        type: '充值',
        times,
        beforeTimes,
        afterTimes,
        remark
      }, { transaction: t });
    } else {
      return res.status(400).json({
        code: 400,
        message: '充值参数错误'
      });
    }

    await t.commit();

    res.json({
      code: 200,
      message: '充值成功',
      data: memberCard
    });

  } catch (error) {
    await t.rollback();
    console.error('会员卡充值错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 会员卡消费
const consumeCard = async (req, res) => {
  const t = await sequelize.transaction();
  try {
    const { cardId, amount, times, remark } = req.body;

    const memberCard = await MemberCard.findByPk(cardId, { transaction: t });
    if (!memberCard) {
      return res.status(404).json({
        code: 404,
        message: '会员卡不存在'
      });
    }

    if (memberCard.status !== '正常') {
      return res.status(400).json({
        code: 400,
        message: '会员卡状态异常，无法消费'
      });
    }

    // 储值卡消费
    if (memberCard.cardType === '储值卡' && amount) {
      if (memberCard.balance < amount) {
        return res.status(400).json({
          code: 400,
          message: '余额不足'
        });
      }

      const beforeBalance = memberCard.balance;
      const afterBalance = Number(beforeBalance) - Number(amount);

      // 更新卡余额
      await memberCard.update({
        balance: afterBalance
      }, { transaction: t });

      // 创建消费记录
      await CardTransaction.create({
        cardId,
        type: '消费',
        amount,
        beforeBalance,
        afterBalance,
        remark
      }, { transaction: t });
    }
    // 次卡消费
    else if (memberCard.cardType === '次卡' && times) {
      if (memberCard.remainingTimes < times) {
        return res.status(400).json({
          code: 400,
          message: '剩余次数不足'
        });
      }

      const beforeTimes = memberCard.remainingTimes;
      const afterTimes = beforeTimes - times;

      // 更新卡次数
      await memberCard.update({
        remainingTimes: afterTimes
      }, { transaction: t });

      // 创建消费记录
      await CardTransaction.create({
        cardId,
        type: '消费',
        times,
        beforeTimes,
        afterTimes,
        remark
      }, { transaction: t });
    } else {
      return res.status(400).json({
        code: 400,
        message: '消费参数错误'
      });
    }

    await t.commit();

    res.json({
      code: 200,
      message: '消费成功',
      data: memberCard
    });

  } catch (error) {
    await t.rollback();
    console.error('会员卡消费错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取交易记录
const getCardTransactions = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, cardId, type, startDate, endDate } = req.body;
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const where = {};
    if (cardId) where.cardId = cardId;
    if (type) where.type = type;
    if (startDate && endDate) {
      where.createdAt = {
        [Op.between]: [startDate, endDate]
      };
    }

    const { count, rows } = await CardTransaction.findAndCountAll({
      where,
      include: [{
        association: 'memberCard',
        include: [{
          association: 'customer',
          attributes: ['name', 'phone']
        }]
      }],
      attributes: {
        include: [
          [
            sequelize.fn('DATE_FORMAT', sequelize.col('CardTransaction.createdAt'), '%Y-%m-%d %H:%i:%s'),
            'createdAt'
          ],
          [
            sequelize.fn('DATE_FORMAT', sequelize.col('CardTransaction.updatedAt'), '%Y-%m-%d %H:%i:%s'),
            'updatedAt'
          ]
        ]
      },
      order: [['createdAt', 'DESC']],
      offset,
      limit: pageSize
    });

    res.json({
      code: 200,
      message: '获取交易记录成功',
      data: {
        total: count,
        page,
        pageSize,
        list: rows
      }
    });

  } catch (error) {
    console.error('获取交易记录错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 通过客户ID获取会员卡列表
const getMemberCardsByCustomerId = async (req, res) => {
  try {
    const { customerId } = req.body;

    if (!customerId) {
      return res.status(400).json({
        code: 400,
        message: '客户ID为必填项'
      });
    }

    const memberCards = await MemberCard.findAll({
      where: { customerId },
      include: [{
        association: 'customer',
        attributes: ['name', 'phone']
      }],
      order: [['createdAt', 'DESC']]
    });

    res.json({
      code: 200,
      message: '获取会员卡列表成功',
      data: memberCards
    });

  } catch (error) {
    console.error('获取会员卡列表错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

module.exports = {
  createMemberCard,
  getMemberCards,
  getMemberCardById,
  updateMemberCard,
  deleteMemberCard,
  rechargeCard,
  consumeCard,
  getCardTransactions,
  getMemberCardsByCustomerId
};